package com.binsoft.ndtta;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

import com.binsoft.ndtta.R;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class ConfigurationActivity extends Activity 
{
	@SuppressWarnings("unused")
	private static final String TAG = "ConfigurationActivity";
	Button mOkButton = null;
	Spinner mTeamSpinner = null;
	Spinner mDivisionSpinner = null;
	TextView mEncryptionKey = null;
	
	int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	private OnItemSelectedListener mDivisionChangeListener = new OnItemSelectedListener() 
	{

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) 
		{
			// Get the selected item
			String selectedDivision = (String)arg0.getSelectedItem();
			
			Team[] teams = null;
			
			if ( selectedDivision.equals("Division 1" ) )
			{
				teams = Constants.div1;
			}
			else if ( selectedDivision.equals("Division 2" ) )
			{
				teams = Constants.div2;
			}
			else
			{
				teams = Constants.div3;
			}
			
			// Setup the team list
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(
					arg1.getContext(), android.R.layout.simple_spinner_item );

			for ( Team team : teams )
			{
				adapter.add( team.name() );
			}
			
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

			mTeamSpinner.setAdapter( adapter );
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) 
		{
		}
	};

	private OnClickListener mOkButtonListener = new OnClickListener()
	{
		final Context context = ConfigurationActivity.this;
		
		private byte[] hexStringToByteArray(String s) 
		{
	        int len = s.length();
	        byte[] data = new byte[len / 2];
	        for (int i = 0; i < len; i += 2) 
	        {
	            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
	                    + Character.digit(s.charAt(i+1), 16));
	        }
	        return data;
	    }
		
		@Override
		public void onClick(View v) 
		{
			// Extract the key from the field
			byte[] encryptionKey = null;
			
			try
			{
				if ( mEncryptionKey.getText().length() > 0 )
				{
					encryptionKey = hexStringToByteArray( mEncryptionKey.getText().toString() );
				}
				else
				{
					// Something gone wrong so fill with something
					encryptionKey = new byte[20];
					SecureRandom random = new SecureRandom();
					random.nextBytes( encryptionKey );
				}
			}
			catch ( Exception e )
			{
				// Something gone wrong so fill with something
				encryptionKey = new byte[20];
				SecureRandom random = new SecureRandom();
				random.nextBytes( encryptionKey );
			}
			
            // Push widget update to surface with newly set prefix
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
			MyWidgetProvider.updateAppWidget(context, appWidgetManager, mAppWidgetId, 
					mDivisionSpinner.getSelectedItemPosition(), mTeamSpinner.getSelectedItemPosition(), encryptionKey );
			
			// Write the prefs
			SharedPreferences.Editor prefs = context.getApplicationContext().getSharedPreferences(Constants.PREFS , Context.MODE_PRIVATE ).edit();		
			prefs.putInt(Constants.TEAM_PREF, mTeamSpinner.getSelectedItemPosition() );
			prefs.putInt(Constants.DIVISION_PREF, mDivisionSpinner.getSelectedItemPosition() );
			try
			{
				prefs.putString( Constants.ENCRYPTION_STRING, new String( encryptionKey, "UTF-8"));
			} 
			catch (UnsupportedEncodingException e)
			{
			};
			
			// Commit the prefs
			prefs.commit();
			
			// Make sure we pass back the original appWidgetId
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
            setResult(RESULT_OK, resultValue);
            
            finish();
		}
	};
	
	private void initialiseDivisions()
	{
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				  this, R.array.DIVISIONS, android.R.layout.simple_spinner_item );

		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		mDivisionSpinner.setAdapter( adapter );
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
        // Set the result to CANCELED.  This will cause the widget host to cancel
        // out of the widget placement if they press the back button.
        setResult(RESULT_CANCELED);

        // Set the view layout resource to use.
        setContentView(R.layout.config_layout);

		// Find the widget id from the intent. 
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) 
        {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // Get handles to the widgets
        mOkButton = (Button)findViewById( R.id.okButton );
        mOkButton.setOnClickListener( mOkButtonListener );
        
        mTeamSpinner = (Spinner)findViewById( R.id.teamSpinner );
        mDivisionSpinner = (Spinner)findViewById( R.id.divisionSpinner );
        mDivisionSpinner.setOnItemSelectedListener( mDivisionChangeListener );
        mEncryptionKey = (TextView)findViewById( R.id.enryptionKey);
      
        // Initialise the divisions spinner
        initialiseDivisions();
	}
}
